<?php

namespace Sharks\Core\Support\Base;

/**
 * 字符串工具类
 */
class Str {

	/**
	 * 字符串是否为空
	 * @param $str
	 * @return bool
	 */
	public static function isEmpty($str) {
		return '' == $str ? true : false;
	}

	/**
	 * 字符串是否无内容
	 * @param $str
	 * @return bool
	 */
	public static function isBlank($str) {
		return static::isEmpty(trim($str));
	}

	/**
	 * 按长度生成随机字符串
	 * @param int $length
	 * @param string $source
	 */
	public static function randStr($length, $source = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz') {

		$result = null;
		$max = strlen($source) - 1;
		for ( $i = 0; $i < $length; $i++ ) {  
			$result .= $source[rand(0, $max)];  
		}  
		return $result;
	}

	/**
	 * 按长度生成随机数字字符串数组
	 * @param  int $length [description]
	 * @return string         [description]
	 */
	public static function randInt($length) {
		return self::randStr($length, '1234567890');
	}

	/**
	 * 随机多个词语
	 * @param $length
	 * @param array $source
	 * @return array
	 */
	public static function randWords($length, $source = array('foo', 'bar')) {

		$result = array();
		$max = count($source) - 1;
		for ($i = 0; i < $length; $i++) {
			$result[] = $source[rand(0, $max)];
		}
		return $result;
	}

	/**
	 * 随机一个词
	 * @param array $source
	 * @return mixed
	 */
	public static function randWord($source = array('foo', 'bar')) {
		return static::randWords(1, $source)[0];
	}
	
	/**
	 * 字符串是否以某单词开头
	 * @param string $str
	 * @param string $needle
	 */
	public static function startsWith($str, $needle) {
		if(0 == strlen($str)) {
			return false;
		}
		if(0 == strlen($needle)) {
			return true;
		}
		return strpos($str, $needle) === 0;
	}
	
	/**
	 * 字符串是否以某单词结尾
	 * @param string $str
	 * @param string $needle
	 */
	public static function endsWith($str, $needle) {
		if(0 == strlen($str)) {
			return false;
		}
		$length = strlen($needle);
		if($length == 0) {
			return true;
		}
		return (substr($str, -$length) === $needle);
	}
}